package com.des1gn.ymgetil.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.des1gn.ymgetil.enums.ApiEnums;
import com.des1gn.ymgetil.model.UserInfoModel;
import com.des1gn.ymgetil.service.ProxyService;
import com.des1gn.ymgetil.service.TaskService;
import com.des1gn.ymgetil.service.UserInfoService;
import com.des1gn.ymgetil.util.AesUtil;
import com.des1gn.ymgetil.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName UserInfoServiceImpl
 * @Description TODO
 * @Author Des1gn
 * @Date 2021/11/23 16:46
 * @Version 1.0
 **/
@Service
@Slf4j
public class UserInfoServiceImpl implements UserInfoService {

    private static Map<String, UserInfoModel> userInfoMap = new ConcurrentHashMap<>();

    @Autowired
    TaskService taskService;

    @Autowired
    ProxyService proxyService;


    @Override
    public UserInfoModel getUserInfo(String sessionId) {
        if (StringUtils.isEmpty(sessionId)){
            return null;
        }
        UserInfoModel result = userInfoMap.get(sessionId);
        if (result != null){
            return result;
        }
        String url = ApiEnums.getApi("获取用户信息");
        JSONObject res = HttpUtil.getOkHttp(url, sessionId,null);
        if (res == null){
            return null;
        }
        JSONObject user = res.getJSONObject("user");
        result = JSONObject.parseObject(JSONObject.toJSONString(user), UserInfoModel.class);
        result.setSessioId(sessionId);
        result.setKey(AesUtil.getKey(sessionId));
        userInfoMap.put(sessionId,result);
        return result;
    }

    @Override
    public Boolean setUserInfo(UserInfoModel userInfo) {
        String url = ApiEnums.getApi("设置用户信息");
        url = url.replaceAll("BIRTHDAY",userInfo.getBirthday());
        url = url.replaceAll("PHONE",userInfo.getTel());
        url = url.replaceAll("USERNAME",userInfo.getCname());
        url = url.replaceAll("SEX",userInfo.getSex());
        url = url.replaceAll("CARDNO",userInfo.getIdcard());
        url = url.replaceAll("CARDTYPE",userInfo.getDoctype());
        url = url.replaceAll("AGE",userInfo.getAge());
        Proxy randomProxy = proxyService.getRandomProxy();
        JSONObject res = HttpUtil.getOkHttp(url, userInfo.getSessioId(),randomProxy);
        if (res == null || res.getInteger("status") != 200){
            return false;
        }
        userInfoMap.put(userInfo.getSessioId(),userInfo);
        return true;
    }

    @Override
    public Boolean removeUserInfo(String sessionId) {
        userInfoMap.remove(sessionId);
        taskService.removeTask(sessionId);
        return true;
    }

    @Override
    public List<UserInfoModel> getUserInfoList() {
        ArrayList<UserInfoModel> userInfoModels = new ArrayList<>(userInfoMap.values());
        return userInfoModels;
    }

    @Override
    public void setNewSessionId(String oldSessionId, String newSessionId) {
        UserInfoModel result = userInfoMap.get(oldSessionId);
        if (result != null){
            userInfoMap.remove(oldSessionId);
            result.setSessioId(newSessionId);
            result.setKey(AesUtil.getKey(newSessionId));
            userInfoMap.put(newSessionId,result);
            //更新任务信息
            taskService.setNewSessionId(oldSessionId,newSessionId);
        }
    }

    @Override
    public void sessionKeepAliave() {
        String url = ApiEnums.getApi("获取用户信息");
        for (String sessionKey : userInfoMap.keySet()){
            try {
                Proxy randomProxy = proxyService.getRandomProxy();
                JSONObject res = HttpUtil.getOkHttp(url, sessionKey,randomProxy);
                if (res == null){
                    continue;
                }
                JSONObject user = res.getJSONObject("user");
                UserInfoModel userInfoModel  = JSONObject.parseObject(JSONObject.toJSONString(user), UserInfoModel.class);
                userInfoModel.setSessioId(sessionKey);
                userInfoMap.put(sessionKey,userInfoModel);
            }catch (Exception e){
                e.printStackTrace();
                log.error("用户session保活错误,{}",e);
            }
        }
    }
}
